<?php

namespace console\db\channels;

use Yii;
use yii\db\Query;
use yii\helpers\Console;
use yii\helpers\ArrayHelper;

/**
 * 数据表直接复制迁移
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
abstract class TransferTableFasterMigration extends TransferTableMigration {

    /**
     * @inheritdoc
     */
    const PART_MAX = 1000000;

    /**
     * @var string 临时增加内存
     */
    public $memorySize = '512M';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $options = $this->getTransferOptions();
        $fields = ArrayHelper::getValue($options, 'columns');
        $columns = $this->getTransferTableColumns($fields);

        $query = $this->buildQuery();
        if (!($query && $query instanceof Query)) {
            $query = (new Query)->from('{{%' . $this->getSourceTable() . '}}');
        }

        $db = $this->getSourceDb();
        $time = microtime(true);
//        $sql = $query->createCommand($db)->getRawSql();
//        Console::output($sql . "\n\ncount times: " . sprintf('%.3f', microtime(true) - $time) . "s.");
        $total = $query->count('*', $db);
        Console::output("count times: " . sprintf('%.3f', microtime(true) - $time) . "s.");
        if (!$total) {
            Console::output("No data transferred.");
            return;
        }
        if ($this->beforeTruncateTargetTable) {
            $this->forceTruncateTable('{{%' . $this->getTargetTable() . '}}');
        }
        $callable = [$this, 'transferTable'];
        $this->handleProgress($query, $callable, $columns, $db, $total);
        $this->afterTransfer($this->getTargetTable());
    }

}
